<?php

namespace app\components;

use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\DetailView;

class BaseDetailView extends DetailView {

    public $options = ['class' => 'table detail-view'];
    public $firstWidth = '';
    public $template = '<tr><td width="{w}" class="text-left">{label}:</td><td class="text-left">{value}</td></tr>';
    public $before = '<tr><th colspan="2" class="text-left">{title}</th></tr>';
    public $title = '';

    public function run() {
        $rows = [];
        if (!empty($this->title)) {
            $rows[] = str_replace('{title}', $this->title, $this->before);
        }

        $i = 0;
        foreach ($this->attributes as $attribute) {
            if (isset($attribute['visible']) && !$attribute['visible']) {
                continue;
            }
            $rows[] = $this->renderAttribute($attribute, $i++);
        }

        $options = $this->options;
        $tag = ArrayHelper::remove($options, 'tag', 'table');
        echo Html::tag($tag, implode("\n", $rows), $options);
    }

    protected function renderAttribute($attribute, $index) {
        $template = isset($attribute['template']) ? $attribute['template'] : $this->template;
        if (is_string($this->template)) {
            return strtr($template, [
                '{label}' => $attribute['label'],
                '{w}' => $this->firstWidth,
                '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
            ]);
        }
        return call_user_func($this->template, $attribute, $index, $this);
    }

    protected function normalizeAttributes() {
//        foreach ($this->attributes as $i => $attribute) {
//            if (is_array($attribute) && isset($attribute['value']) && empty($attribute['value'])) {
//                unset($this->attributes[$i]);
//                continue;
//            }
//        }
        parent::normalizeAttributes();
    }
}